
package com.zws.cucumber.boostrap;

import com.github.tomakehurst.wiremock.WireMockServer;
//import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;
import com.zws.cucumber.ZwsConstants;
import com.zws.cucumber.ZwsUtils;
import com.zws.cucumber.wiremock.listener.ZwsStubTimeoutMarker;
import com.zws.cucumber.wiremock.transformer.ZwsJsonBodyUnquoteValueResponseTransformer;
import com.zws.cucumber.wiremock.transformer.ZwsStatusResponseTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;

/**
 * author: zws
 */
public class ZwsWiremockBootstrap {

    private static long timestamp = 0L;

    private static long startTimer() {
        return timestamp = System.currentTimeMillis();
    }

    private static long elapsed() {
        long elapsed = System.currentTimeMillis() - timestamp;
        timestamp = System.currentTimeMillis();
        return elapsed;
    }

    private static void println(Object msg) {
        System.out.println(msg);
    }

    private static void printf(String format, Object... args) {
        System.out.printf(format, args);
    }

    public static WireMockServer getWireMockServer() {
        try {
            println("boot embedded wiremock");
            return bootEmbeddedWireMockServer();
        } catch (Exception e) {
            println("boot wiremock failed, exit!");
            e.printStackTrace();
            System.exit(1);
            return null;
        }
    }

    private static WireMockServer bootEmbeddedWireMockServer() {
        startTimer();

        WireMockServer wireMockServer = new WireMockServer(options()
            .stubRequestLoggingDisabled(true)
//            .port(ZwsUtils.nextPort("wiremock"))
//            .port(ZwsConstants.WIREMOCK_PORT)
            .port(8088)
            .extensions(
                // transformer
                new ZwsJsonBodyUnquoteValueResponseTransformer(),
//                new ResponseTemplateTransformer(false),
                new ZwsStatusResponseTransformer(),
                // listener
                new ZwsStubTimeoutMarker()));

        wireMockServer.start();

        printf("boot embedded wiremock done, elapsed: %dms\n", elapsed());

        return wireMockServer;
    }


}
